package com.zcr.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @version 1.0
 * @author： 张诚
 * @date： 2021-03-04 10:00
 */
@Controller
@Slf4j
public class ManagerController {

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String login(String loginname, String pwd, Model model, HttpSession session){
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(loginname,pwd);
        try {
            subject.login(token);
//            subject.getSession().setAttribute("LoginUser",subject.getPrincipal());
            session.setAttribute("LoginUser",subject.getPrincipal());
            return "redirect:/index";
        } catch (Exception ex) {
            log.error("用户登入失败",ex);
            model.addAttribute("loginErr","用户名或密码错误");
            return "login";
        }
    }

}
